package simonxianyu.learn.springmybatis.util;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Iterator;

/**
 * Use this to resolver DataTableInput from WebRequest.
 * Created by simon on 16/8/18.
 */
public class DataTableInputResolver implements HandlerMethodArgumentResolver {
  @Override
  public boolean supportsParameter(MethodParameter methodParameter) {
    return DataTableInput.class.equals(methodParameter.getParameterType());
  }

  @Override
  public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
    DataTableInput req = new DataTableInput();
    req.setDraw(getInteger("draw", webRequest));
    req.setStart(getInteger("start",0, webRequest));
    req.setLength(getInteger("length",30, webRequest));
    Iterator<String> itName = webRequest.getParameterNames();

    String lastName = "startColumn";
    while (itName.hasNext()) {
      String name = itName.next();
      if (name.startsWith(lastName)) {
        continue;
      }
      if (name.startsWith("columns[")) {
        int p = name.indexOf(']');
        String colName = name.substring(0, p+1);
        DataTableInputColumn col = new DataTableInputColumn();
        col.setData(webRequest.getParameter(colName+"[data]"));
        col.setName(webRequest.getParameter(colName+"[name]"));
        col.setSearchable(Boolean.parseBoolean(webRequest.getParameter(colName+"[searchable]")));
        col.setOrderable(Boolean.parseBoolean(webRequest.getParameter(colName+"[orderable]")));
        col.setSearchValue(webRequest.getParameter(colName+"[search][value]"));
        col.setSearchRegex(Boolean.parseBoolean(webRequest.getParameter(colName+"[search][regex]")));
        req.addColumn(col);
        lastName = colName;
      } else if ("search[value]".equals(name)) {
        req.setSearchValue(webRequest.getParameter(name));
      } else if ("search[regex]".equals(name)) {
        req.setSearchIndex(webRequest.getParameter(name));
      }
    }
    return req;
  }

  private Integer getInteger(String draw, NativeWebRequest webRequest) {
    String p = webRequest.getParameter(draw);
    return p!=null ? Integer.parseInt(p):null;
  }
  private Integer getInteger(String draw, Integer defaultV, NativeWebRequest webRequest) {
    String p = webRequest.getParameter(draw);
    return p!=null ? Integer.parseInt(p):defaultV;
  }
}
